package com.xhwl.centiotdata.handler.talk.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.talk.TalkIntegrationFactory;
import com.xhwl.centiotdata.handler.talk.TalkIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.dnake.DeviceDnakeDTO;
import com.xhwl.centiotdata.pojo.dto.talkback.TalkBackIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.ICentTalkBackService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.suppliersystem.dnake.DeviceDnakeHandler;
import com.xhwl.centiotdata.suppliersystem.dnake.TalkDnakeHandler;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: wuyuhao
 * @createDate: 2022/12/23 14:10
 */
@Service
public class TalkDnakeIntegrationHandler extends TalkIntegrationHandler {

    private static final Logger log = LoggerFactory.getLogger(TalkDnakeIntegrationHandler.class);

    @Resource
    IDeviceCentService deviceCentService;

    @Resource
    DeviceDnakeHandler deviceDnakeHandler;

    @Resource
    TalkDnakeHandler talkDnakeHandler;

    @Resource
    ICentTalkBackService talkBackService;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 狄耐克云对讲
        TalkIntegrationFactory.register(95, this);
    }

    @Override
    public void pullDevice(TalkBackIntegrationConfigDTO configDTO) {
        if (configDTO.getDeviceType() == null) {
            log.error("projectId: {} pullDevice failed! deviceType is null!", configDTO.getProjectId());
            return;
        }
        if (!configDTO.getDeviceType().equals(DeviceTypeEnum.TALK_BACK.getCode())) {
            return;
        }
        // 拉取数据
        List<DeviceDnakeDTO> deviceDnakeDTOList = deviceDnakeHandler.pullDevice(configDTO.getProjectId());
        if (CollectionUtils.isEmpty(deviceDnakeDTOList)) {
            return;
        }
        // 转换数据
        List<DeviceDTO> deviceDTOList = this.handleDevice(configDTO, deviceDnakeDTOList);
        // 存储业务中台
        deviceCentService.asyncUpdateDevice(deviceDTOList);
    }

    private List<DeviceDTO> handleDevice(TalkBackIntegrationConfigDTO configDTO, List<DeviceDnakeDTO> deviceDnakeDTOList) {
        // 批量添加狄耐克云对讲设备sip账号
        List<String> uids = deviceDnakeDTOList.stream().map(DeviceDnakeDTO::getUid).collect(Collectors.toList());
        Map<String, String> mapSip = talkBackService.addDeviceSip(configDTO.getProjectId(), uids);
        log.info("获取到的map<uid, sip>为: {}", mapSip);
        return deviceDnakeDTOList.stream()
                .map(deviceDnakeDTO -> {
                    // 狄耐克设备设置sip账号操作
                    String uid = deviceDnakeDTO.getUid();
                    talkDnakeHandler.setSip(configDTO, uid, mapSip.get(uid));
                    // 狄耐克设备属性组装
                    DeviceDTO deviceDTO = new DeviceDTO();
                    deviceDTO.setProjectId(configDTO.getProjectId());
                    deviceDTO.setProductId(configDTO.getProductId());
                    deviceDTO.setCategoryId(configDTO.getCategoryEnum().getId());
                    deviceDTO.setDeviceTypeId(configDTO.getDeviceType());
                    String name = deviceDnakeDTO.getBuild() + "栋" + deviceDnakeDTO.getUnit() + "单元" + deviceDnakeDTO.getFloor() + "楼" + deviceDnakeDTO.getFamily() + "房";
                    deviceDTO.setName(name);
                    deviceDTO.setThirdDeviceId(uid);
                    deviceDTO.setOnlineStatus(deviceDnakeDTO.getOnline());
                    // 路址处理，如果有第二个，那么默认是路址id
                    String[] split = deviceDnakeDTO.getItemNumber().split("-");
                    if (split.length > 1 && split[1].matches("\\d+")) {
                        String locationId = split[1];
                        deviceDTO.setOrganizationId(Integer.parseInt(locationId));
                    }
                    // 云对讲设备
                    JSONObject attributeJson = new JSONObject();
                    attributeJson.put("ip", deviceDnakeDTO.getIp());
                    // 狄耐克设备类型：分机：0100 门口机：0101 小门口机：0102 围墙机 0103 管理机:0104
                    // 云对讲设备类型 1小区围墙机，2单元门口机，3室内机
                    if ("0103".equals(deviceDnakeDTO.getDeviceType())) {
                        deviceDTO.setAppLabel(1);
                        attributeJson.put("DeviceType", 1);
                    } else if ("0101".equals(deviceDnakeDTO.getDeviceType())) {
                        deviceDTO.setAppLabel(2);
                        attributeJson.put("DeviceType", 2);
                    }
                    deviceDTO.setAttributeJson(attributeJson);
                    return deviceDTO;
                }).collect(Collectors.toList());
    }

}
